<template>
  <div class="h100">
    <v-tree @getOrgId="getOrgId" :params="dParams">
      <el-button
        type="default"
        icon="el-icon-refresh-right"
        class="ml10 pd10"
        slot="search"
        title="同步"
        :loading="syncLoading"
        @click="update"
      ></el-button>
      <span slot="content" class="content" slot-scope="curNum">
        <t-count :dParams="dParams" :curNum="curNum"></t-count>
        <!-- <el-radio-group v-model="params.status">
          <el-radio-button :label="2">待上报</el-radio-button>
          <el-radio-button :label="1">已上报</el-radio-button>
          <el-radio-button :label="3">待绑定</el-radio-button>
          <el-radio-button :label="4">已绑定</el-radio-button>
        </el-radio-group>-->
        <div class="tab-content">
          <div class="listbox">
            <v-list
              v-if="params.department"
              :api="api.getUrl"
              ref="list"
              cards="1"
              :cols="cols"
              :params="params"
            >
              <template slot="search">
                <!-- <el-dropdown trigger="click" @command="operateBatch">
                  <el-button size="small" class="ml10" :disabled="!checkedArr.length">
                    批量操作
                    <el-icon type="ios-arrow-down"></el-icon>
                  </el-button>
                  <el-dropdownMenu slot="dropdown">
                    <el-dropdownItem command="1" disabled>批量上报</el-dropdownItem>
                    <el-dropdownItem command="0" disabled>批量撤销上报</el-dropdownItem>
                    <el-dropdownItem command="2">批量绑定</el-dropdownItem>
                    <el-dropdownItem command="3">批量解绑</el-dropdownItem>
                    <el-dropdownItem command="4">批量设置上传</el-dropdownItem>
                    <el-dropdownItem command="5">批量设置只读</el-dropdownItem>
                  </el-dropdownMenu>
                </el-dropdown>-->
                <!-- <el-button
                  size="mini"
                  title="立即上报"
                  type="default"
                  circle
                  style="position: absolute;right: 0;"
                >立即上报</el-button>-->
              </template>
              <template slot="head" slot-scope="head">
                <t-header
                  :to="dParams.order_by"
                  :head="head"
                  :checkedArr="checkedArr"
                  :selectAll="selectAll"
                ></t-header>
              </template>
              <template slot="item" slot-scope="props">
                <t-item
                  :props="props"
                  :to="dParams.order_by"
                  :checkShowArr="checkShowArr"
                  :selectItem="selectItem"
                  :operate="operate"
                ></t-item>
              </template>
            </v-list>
          </div>
        </div>
      </span>
    </v-tree>
    <v-warnmodal :modShow.sync="batchModShow" :log="diaLog" :logSubmit="submit"></v-warnmodal>
    <!-- 上报、撤销提示 -->
    <el-dialog :title="`${diaLog.title}`" :visible.sync="diaLogShow" width="30%">
      <template v-if="modData.show">
        <div class="delCol">
          <span>ID：</span>
          <span>{{ modData.data.instance_id }}</span>
        </div>
        <div class="delCol">
          <span>IP：</span>
          <span>{{ modData.data.ip_address }}</span>
        </div>
        <div class="delCol">
          <span>部门：</span>
          <span>{{ modData.data.department_name }}</span>
        </div>
        <div class="delCol">
          <span>资源集：</span>
          <span>暂无</span>
        </div>
        <div class="delCol">
          <span>申请人：</span>
          <el-select v-model="value" placeholder="请选择" style="width:calc(100% - 65px)">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 绑定提示 -->
    <el-dialog title="绑定" :visible.sync="bindMod.show" width="30%">
      <div class="delCol">
        <span>ID：</span>
        <span style="width:calc(100% - 65px);display: inline-block;">{{ bindMod.data.instance_id }}</span>
      </div>
      <div class="delCol">
        <span>用户：</span>
        <el-select
          v-model="bindMod.bindValue"
          filterable
          placeholder="请选择"
          style="width:calc(100% - 65px)"
        >
          <el-option
            v-for="item in userList"
            :key="item.uid"
            :label="item.realname"
            :value="item.uid"
          ></el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="bindMod.show = false">取 消</el-button>
        <el-button v-if="command" type="primary" @click="batchBindSubmit">确 定</el-button>
        <el-button v-else type="primary" @click="bindSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 详情开始 -->
    <v-baseinfo v-model="drawer.show" :name="drawer.name">
      <div class="wrapper-content" v-if="drawer.data" slot="org/home">
        <div class="content-item">
          <span class="label">实例名称：</span>
          <span class="value">{{drawer.data.instance_name || '-'}}</span>
        </div>
      </div>
    </v-baseinfo>
    <!-- 详情结束 -->
  </div>
</template>

<script>
import THeader from "../commpoents/table_header";
import TItem from "../commpoents/table_item";
import TCount from "../commpoents/count_total";
export default {
  components: {
    THeader,
    TItem,
    TCount
  },
  watch: {
    $route: {
      handler(to, form) {
        this.initReq(to);
      }
    }
  },
  data() {
    return {
      params: {
        type: "aliyun",
        department: ""
      },
      value: null,
      diaLogShow: false,
      batchModShow: false,
      modData: {
        show: false
      },
      bindMod: {
        show: false,
        data: {},
        bindValue: null
      },
      syncLoading: false,
      checkArr: [], // 存id--全选使用
      checkedArr: [], // 筛选后的id--请求使用
      checkShowArr: {}, // 存显示状态
      diaLog: {
        title: "提示",
        msg: "上报",
        params: []
      },
      command: null,
      options: [
        { value: 1, label: "小明" },
        { value: 2, label: "小话" },
        { value: 3, label: "小军" }
      ],
      userList: [],
      reqFail: false, // 请求失败，批量操作结束
      is_up: 0, // 是否只可读
      drawer: {
        show: false,
        data: null,
        name: "IRS上报"
      },
      api: {
        getUrl: "",
        syncUrl: ""
      },
      dParams: {
        order_by: ""
      },
      mod: "",
      cols: ""
    };
  },
  methods: {
    submit() {
      if (this.command === "3") {
        // 批量解绑
        this.batchBindSubmit();
      } else if (this.command === "4") {
        // 批量可上传
        this.is_up = 1;
        this.batchSetStatus();
      } else if (this.command === "5") {
        // 批量可读
        this.is_up = 0;
        this.batchSetStatus();
      }
    },
    cancel() {
      this.diaLogShow = false;
      this.modData.show = false;
    },
    update() {
      this.syncLoading = true;
      this.$api.jget(this.api.syncUrl).then(res => {
        if (res.status === 1) {
          this.$success(res.msg);
        } else {
          this.$error(res.msg);
        }
        this.syncLoading = false;
      });
    },
    // 批量操作
    operateBatch(type) {
      // 标识批量操作
      this.command = type;
      switch (type) {
        case "0":
          this.diaLog.msg = "设置撤销上报";
          break;
        case "1":
          this.diaLog.msg = "设置上报";
          break;
        case "2":
          this.diaLog.msg = "设置绑定";
          this.bindMod.bindValue = null;
          this.bindMod.data.instance_id = this.checkedArr.join("，");
          this.bindMod.show = true;
          break;
        case "3":
          this.diaLog.msg = "设置解绑";
          this.bindMod.bindValue = 0;
          this.batchModShow = true;
          break;
        case "4":
          this.diaLog.msg = "设置可上报";
          this.batchModShow = true;
          break;
        case "5":
          this.diaLog.msg = "设置只读";
          this.batchModShow = true;
          break;
        default:
          this.diaLog.msg = "提示";
          break;
      }
      // this.batchModShow = true;
    },
    // 单个操作
    operate(item, status) {
      this.diaLogShow = true;
      this.modData.show = true;
      this.modData.data = item;
    },
    // 获取左侧组织id
    getOrgId(val) {
      if (this.params.department !== val) {
        this.params.department = val;
      }
    },

    selectItem() {
      setTimeout(() => {
        let keyArr = [];
        Object.keys(this.checkShowArr).forEach((el, inx) => {
          if (this.checkShowArr[el]) {
            keyArr.push(el);
          }
        });
        this.checkedArr = keyArr;
      });
    },
    selectAll(dataR) {
      if (this.checkArr.length) {
        this.checkArr = [];
        this.checkedArr = [];
        this.checkShowArr = {};
      } else {
        dataR.forEach(el => {
          let id =
            el.instance_id || el.DBInstanceId || el.Name || el.LoadBalancerId;
          this.checkArr.push(id);
          this.checkShowArr[id] = true;
        });
        this.selectItem();
      }
    },
    // 绑定、解绑
    bindServer(item, isBind) {
      // 单独绑定时初始化command
      this.command = null;
      this.bindMod.data = item;
      if (!isBind) {
        this.bindMod.bindValue = 0;
        this.bindSubmit();
      } else {
        this.bindMod.show = true;
        this.bindMod.bindValue = "";
      }
    },
    // 批量/单个操作
    reqSub() {
      return new Promise((resolve, rej) => {
        this.reqFail = false;
        let params = {};
        params.uid = this.bindMod.bindValue;
        switch (this.mod) {
          case "ecs":
            params.instance_id = this.bindMod.data.instance_id;
            break;
          case "rds":
            params.DBInstanceId = this.bindMod.data.instance_id;
            break;
          case "oss":
            params.Name = this.bindMod.data.instance_id;
            break;
          case "slb":
            params.LoadBalancerId = this.bindMod.data.instance_id;
            break;
          case "redis":
            params.InstanceId = this.bindMod.data.instance_id;
          default:
            break;
        }
        this.$api.jget(`instance.${this.mod}_bind_user`, params).then(res => {
          if (res.status === 1) {
            this.$success(res.msg);
            this.bindMod.show = false;
            resolve(this.reqFail);
          } else {
            this.reqFail = true;
            this.$error(res.msg);
            rej(this.reqFail);
          }
        });
      });
    },
    bindSubmit() {
      this.reqSub();
      this.$refs.list.fetchData();
      this.checkShowArr = {};
    },
    async batchReqSub(callback) {
      this.bindMod.data.instance_id = this.checkedArr[0];
      this.checkedArr.splice(0, 1);
      await callback().then(res => {
        if (this.reqFail) {
          return;
        }
        if (this.checkedArr.length) {
          this.batchReqSub(callback);
        } else {
          this.$refs.list.fetchData();
        }
      });
    },
    batchBindSubmit() {
      this.batchReqSub(this.reqSub);
      this.checkShowArr = {};
    },
    // 上报
    setStatus() {
      return new Promise((resolve, rej) => {
        this.reqFail = false;
        let params = {};
        params.is_up = this.is_up;
        switch (this.mod) {
          case "ecs":
            params.instance_id = this.bindMod.data.instance_id;
            break;
          case "rds":
            params.DBInstanceId = this.bindMod.data.instance_id;
            break;
          case "oss":
            params.Name = this.bindMod.data.instance_id;
            break;
          case "slb":
            params.LoadBalancerId = this.bindMod.data.instance_id;
            break;
          case "redis":
            params.InstanceId = this.bindMod.data.instance_id;
          default:
            break;
        }
        this.$api.jget(`instance.set_${this.mod}_up`, params).then(res => {
          if (res.status === 1) {
            this.$success(res.msg);
            resolve();
          } else {
            this.$error(res.msg);
            this.reqFail = true;
            rej();
          }
        });
      });
    },
    batchSetStatus() {
      this.batchReqSub(this.setStatus);
      this.checkShowArr = {};
    },
    getUserList() {
      this.$api.jget("user.get_user_list").then(res => {
        if (res.status === 1) {
          this.userList = res.data.list;
        }
      });
    },
    setBaseInfo(item) {
      this.drawer.show = true;
      this.drawer.data = item;
    },
    initReq(route) {
      let mod = route.path.split("/")[3];
      this.mod = mod;
      if (mod === "ecs") {
        this.api.getUrl = `instance.get_${mod}`;
      } else {
        this.api.getUrl = `instance.get_aliyun_${mod}`;
      }
      this.api.syncUrl = `instance.sync_aliyun_${mod}`;
      switch (mod) {
        case "ecs":
          this.cols =
            "60,150,100,100,100,100,100,100,100,150,100,100,100,100,100";
          break;
        case "rds":
          this.cols = "60,150,100,100,100,100,100,100,100,100";
          break;
        case "oss":
          this.cols = "60,150,100,100,100,100,100,100";
          break;
        case "slb":
          this.cols = "60,150,100,100,100,100,100,100,150";
          break;
        case "redis":
          this.cols = "60,150,100,100,100,100,100,100,100,150";
          break;
        default:
          break;
      }
      this.dParams.order_by = `aliyun_${mod}`;
    }
  },
  mounted() {
    this.initReq(this.$route);
    this.getUserList();
  }
};
</script>

<style lang="scss" scoped>
.delCol {
  padding: 6px 40px;
  & > span:first-child {
    display: inline-block;
    width: 60px;
  }
}
/deep/.listbox {
  table.table th,
  table.table td {
    white-space: nowrap;
  }
}
.statistic {
  height: 80px;
  border: 1px solid #efefef;
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-bottom: 20px;
  & > div {
    text-align: center;
    .value {
      margin: 5px 0;
    }
  }
}
</style>